#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import time
import sys
import threading
import signal
from pynput.keyboard import Key, Controller as c_keyboard
import logging
import argparse
import shutil
keyboard = c_keyboard()

filename='test'
sltime=120
lock=threading.Lock()

def ospen(cmdstr):
    xxpid=os.popen(cmdstr,"r")
    pid=xxpid.read()
    xxpid.close()
    #print("pid: "+str(pid))
    return pid

def openfile(filename):
    try:

        temp ="wps "+filename+" > out.put 2>&1 &"
        print("openwps :"+temp)
        os.system(temp)
    except Exception as e:
        print('openfile:'+ str(e))

#获取目录下的所有doc 文件字符串
def getdirfilename(dir):
    #print(dir)
    filelisttemp = os.listdir(dir)
    #print(filelisttemp)
    filename= ''
    for name in filelisttemp:
        #print("getdirfilename")
        #print(filelisttemp)
        if(('doc' in name) and ('~' not in name) and ('bak' not in name) and (name.startswith('.') == False)):
            filename= filename + ' '+name
    return filename

#将目录字符串进行拆分
def getdirlist(dirstring):
    #dirlist=list(filter(None,dirstring.split(' ')))
	dirlist=[x for x in dirstring.split(' ') if x]
	print("getdirlist [x for x in dirstring.split(' ') if x]")
	print(dirlist)
	return dirlist

#删除隐藏文件
def clearhidefile(dir,filelist=''):
	filelisttemp = os.listdir(dir)
	print(filelisttemp)
	if(filelist !=''):
		filelisttemp=getdirlist(filelist)
	print(filelisttemp)
	for name in filelisttemp:
		if(('.~'  in name) or (name.startswith('.') == True)):
			os.remove(os.path.join(dir,name))
			print('remove 隐藏文件:'+os.path.join(dir,name))

def createfile(filename):
    print("创建1000个doc文件")
    for index in range(1,1001):
        filepath= os.path.join('./',filename+str(index)+'.doc')
        file = open(filepath,'a')
        file.write('loss:'+str(index))
        file.close()

def existsfile(filename):
    print("判断文件是否丢失:")
    for index in range(1,1):
        filepath= os.path.join('./',filename)
        if(os.access(filepath,os.W_OK)==False):
            print(filepath+"           文件丢失！！！！！")
            os.system("echo "+filepath+" >> lossfileName.txt")
        else:
            openfile(filepath)

def deletefile(filename):
    print("删除1000个doc文件")
    for index in range(1,1):
        filepath= os.path.join('./',filename+str(index)+'.doc')
        os.remove(filepath)

def savedocfile(save):
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    print("enter")
    keyboard.release(Key.enter)
    print("ctrl + s 保存文件")
    keyboard.press(Key.ctrl)
    keyboard.press('s')
    time.sleep(0.5)
    keyboard.release('s')
    keyboard.release(Key.ctrl)
    time.sleep(save)
    time.sleep(0.1)
    keyboard.press(Key.enter)
    print("ctrl + s -> enter")
    time.sleep(0.1)
    keyboard.release(Key.enter)
    keyboard.press(Key.enter)
    time.sleep(0.1)
    print("ctrl + s -> enter")
    keyboard.release(Key.enter)
    pass

def inputkeyboard(temp):
    print("输入字符："+temp)
    for te in temp:
        keyboard.press(te)
        time.sleep(0.4)
        keyboard.release(te)
        pass

def killfunc(pid):
    if str(pid)!="0":
        try:
            re= os.system("kill -9 "+str(pid))
            if(re==0):
                print("kill -9  "+str(pid))
                pass
        except Exception as e:
            pass

def closefile(filename):
    try:
               print("关闭文档："+filename)
               for i in range(2):
                   pid=ospen("ps -ef  |  grep '/opt/kingsoft/wps-office/office6/wps"+filename+"' |grep -v 'color=auto' | awk '{print $2}' | sed -n 1p ")
                   print("ps -ef  |  grep '/opt/kingsoft/wps-office/office6/wps"+filename+"' |grep -v 'color=auto' | awk '{print $2}' ")
                   print(pid)
                   if(pid!=''):
                       killfunc(pid)
                   time.sleep(1)
                   pid=ospen("ps -ef  |  grep '/opt/kingsoft/wps-office/office6/wps"+filename+"' |grep -v 'color=auto' | awk '{print $2}' | sed -n 1p")
                   print("ps -ef  |  grep '/opt/kingsoft/wps-office/office6/wps"+filename+"' |grep -v 'color=auto' | awk '{print $2}' | sed -n 1p")
                   print(pid)
                   if(pid!=''):
                       killfunc(pid)
                   time.sleep(0.1)
                   pid=ospen("ps -ef  | grep -v 'color=auto' | grep '/usr/bin/wps"+filename+"' | awk '{print $2}' | sed -n 1p")
                   print("ps -ef  | grep -v 'color=auto' | grep '/usr/bin/wps"+filename+"' | awk '{print $2}' | sed -n 1p")
                   print(pid)
                   if(pid!=''):
                       killfunc(pid)
                   time.sleep(0.1)
                   pid=ospen("ps -ef  | grep -v 'color=auto' | grep '/opt/kingsoft/wps-office/office6/wps"+filename+"' | awk '{print $2}' | sed -n 2p")
                   print("ps -ef  | grep -v 'color=auto' | grep '/opt/kingsoft/wps-office/office6/wps"+filename+"' | awk '{print $2}' | sed -n 2p")
                   print(pid)
                   if(pid != ''):
                       killfunc(pid)
                   time.sleep(0.1)
                   pid=ospen("ps -ef  | grep -v 'color=auto' | grep '/usr/bin/wps"+filename+"' | awk '{print $2}' | sed -n 2p")
                   print("ps -ef  | grep -v 'color=auto' | grep '/usr/bin/wps"+filename+"' | awk '{print $2}' | sed -n 2p")
                   print(pid)
                   if(pid != ''):
                       killfunc(pid)
    except Exception as e:
        if(lock.locked()):
            print(" closewps lock.release")
            print('callback:'+ str(e))
    pass
#创建1
def cleartmpdirctory():
	rmpath='/root/.local/share/Kingsoft/office6/data/backup/'
	if(os.path.exists(rmpath)):
		os.system("rm -rf /root/.local/share/Kingsoft/office6/data/backup/*")

def openandedit(index,filelist,timesleep,save,ctrlf4,args):
    openfile(filelist)
    print('timesleep:'+str(timesleep))
    time.sleep(timesleep)
    if(save!=0):
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)

        inputkeyboard(args.input)

        savedocfile(save)
        if(ctrlf4==1):
                print('alt + f4 ')
                keyboard.press(Key.alt_l)
                keyboard.press(Key.f4)
                time.sleep(0.3)
                keyboard.release(Key.f4)
                keyboard.release(Key.alt_l)
                print('alt + ffffffffffffffffffffffffffffffffffffffff4 ')
        closefile(filelist)


#具体操作
def practise(index,filelist,timesleep,save,ctrlf4,args):
	if(args.serial==0):
		openandedit(index,filelist,timesleep,save,ctrlf4,args)

	if(args.serial==1):
		filelisttemp = getdirlist(filelist)
		for filesingle in filelisttemp:
			print("filesingle:"+filesingle)
			openandedit(index," "+filesingle,timesleep,save,ctrlf4,args)
    #清楚目录文件
	print('rm -rf /root/.local/share/Kingsoft/office6/data/backup/*')
	cleartmpdirctory()
	logging.info("  已执行次数： "+str(index))
	index+=1
	pass


#将文件改名为bak，再从bak拷贝一份为原始名称
def copyfilebak(filelist,copywaittime,lastcopydel):
    print("进入"+filelist)
    #获取单个文件名列表
    templist=filelist.split(' ')
    while '' in templist:
        templist.remove('')
    filel=[]
    #取最后一个元素
    if(lastcopydel==1):
        filel.append(templist[-1])
        print(filel)
    else:
        filel=templist
        print(filel)
        pass
    for file in filel:
        #将被打开的文件重命名为bak
        print("重命名"+file +" to "+ file+'.bak')
        os.rename(file,file+'.bak')
    os.listdir('./')
    #拷贝文件名
    for file in filel:
        print("拷贝"+file +'.bak' +" to "+ file)
        shutil.copyfile(file+'.bak',file)
    time.sleep(copywaittime)
    os.listdir('./')
    for file in filel:
        print("删除"+file+'.bak')
        os.remove(file+'.bak')
    time.sleep(copywaittime)
    os.listdir('./')
    pass

if __name__ == '__main__':
    if(sys.argv[1]=='--help' or sys.argv[1]=='-h'):
        print('--files 用来指定要打开的文件名列表')
        print('--timesleep 用来指定等待时间，单位是秒')
        print('--save 用来指定是否输入1个字符以及保存文件，不输入则不会对文档输入1以及保存文档')
        print('--dir 用来遍历目录列表，并依次打开目录里的所有word文件')
        print('--renamecopydel 源文件修改名称file为file.bak，再考本一个file,并将file.bak删除，不对.开头的隐藏文件进行操作')
        print('--copywaittime file.bak，考本一个file需要等待的时间')
        print('--lastcopydel 只对最后一个文件进行重命名，拷贝，删除操作')
        print('--ctrlf4 默认关闭wps进程，但如果该值为1则使用Ctrl+F4来关闭文档')
        print('--input 默认输入1，但添加input后可以制定输入内容')
        print('--serial 默认输入0，但目录中的文档一个接着一个打开，输入，保存，关闭。')
        print('例子：edite1000doc --files="214.doc 215.doc 216.doc" --timesleep=120 --save=1 --renamecopydel=0')
        print('例子：edite1000doc --dir="./test1/ ./test2/ ./test3/" --timesleep=120 --save=1 --renamecopydel=1 --copywaittime=1 --lastcopydel=1 --ctrlf4=1')
        print('|')
        print('|')

    parser = argparse.ArgumentParser()
    parser.add_argument('--files',type=str,default='214.doc 215.doc 216.doc 217.doc 218.doc 219.doc 220.doc 221.doc 222.doc 223.doc')
    parser.add_argument('--timesleep',type=int,default=120)
    parser.add_argument('--save',type=int,default=0)
    parser.add_argument('--dir',type=str,default=None)
    parser.add_argument('--renamecopydel',type=int,default=0)
    parser.add_argument('--copywaittime',type=int,default=1)
    parser.add_argument('--lastcopydel',type=int,default=0)
    parser.add_argument('--ctrlf4',type=int,default=0)
    parser.add_argument('--input',type=str,default='1')
    parser.add_argument('--serial',type=int,default=0)
    args=parser.parse_args()

    #如果存在则打开
    ztq=time.asctime(time.localtime(time.time()))
    logging.basicConfig(filename='ztq_'+str(ztq)+'.log',level=logging.INFO)
    index=0
    filelist=''
    cwd=os.getcwd()
    keyinput=args.input
    print(cwd)
    while True:
        localtime = time.asctime(time.localtime(time.time()))
        try:
            if(args.dir != None):
                list=getdirlist(args.dir)
                for dd in list:
                    try:
                        filelist=getdirfilename(dd)
                        os.chdir(dd)
                        print(os.getcwd())
                        print(filelist)
                        practise(index,filelist,args.timesleep,args.save,args.ctrlf4,args)
                        #是否进行重命名，拷贝，删除操作
                        if(args.renamecopydel==1):
                            copyfilebak(filelist,args.copywaittime,args.lastcopydel)
                        os.chdir(cwd)
                        print(os.getcwd())
                        clearhidefile(dd,'')
                    except Exception as e:
                        logging.error("程序异常终止："+localtime)
                        logging.error(str(e))
                        print(str(e))
                        os.chdir(cwd)
                        clearhidefile(dd,'')
                
            else:
                filelist=args.files
                practise(index,filelist,args.timesleep,args.save,args.ctrlf4,args)
                #是否进行重命名，拷贝，删除操作
                if(args.renamecopydel==1):
                    #是否只对最后一个文件进行操作
                    copyfilebak(filelist,args.copywaittime,args.lastcopydel)
                clearhidefile(dd,filelist)

        except Exception as e:
            logging.error("程序异常终止："+localtime)
            logging.error(str(e))
            print(str(e))
            os.chdir(cwd)
